<template>
  <view class="login-page">
    <view v-if="!forms.avatar" class="login-title">
      您好，
      <p>欢迎使用智慧消防</p>
    </view>
    <view class="login-body">
      <uv-form
        labelPosition="top"
        :model="forms"
        :rules="rules"
        ref="formRef"
        :label-style="{
          color: '#212121',
          fontSize: '32rpx',
        }"
      >
        <uv-form-item label="登录账号" label-width="160rpx" prop="username" borderBottom>
          <uv-input
            v-if="!forms.avatar"
            v-model="forms.username"
            placeholder="请输入您的登录账号"
            border="none"
            maxlength="20"
            clearable
            placeholder-style="fontSize: 28rpx, color: #BDBDBD"
            :customStyle="{
              fontSize: '28rpx',
              height: '80rpx',
            }"
          />
          <view class="login-username" v-else>{{ sensitive(forms.username) }}</view>
        </uv-form-item>
        <uv-form-item label="密码" label-width="160rpx" prop="password" borderBottom>
          <uv-input
            v-model="forms.password"
            placeholder="请输入您的密码"
            border="none"
            :type="showPassword ? 'text' : 'password'"
            maxlength="20"
            clearable
            placeholder-style="fontSize: 28rpx, color: #BDBDBD"
            :customStyle="{
              fontSize: '28rpx',
              height: '80rpx',
            }"
            suffix-icon="eye-fill"
            :suffix-icon-style="{
              color: showPassword ? '#212121' : '#BDBDBD',
            }"
            @suffix="() => (showPassword = !showPassword)"
          />
        </uv-form-item>
        <view class="login-button" :class="{ disabled: disabled }" @click="handleLogin"
          >登录</view
        >
      </uv-form>
      <view class="ss-flex ss-row-right">
        <view class="login-btn" @click="handleForgot"> 忘记密码？ </view>
      </view>
      <template v-if="!forms.avatar">
        <uv-divider
          text="第三方登录"
          text-size="28rpx"
          text-color="#BDBDBD"
          line-color="#E6F1E9"
          style="margin: 60rpx"
        />
        <view class="ss-flex ss-row-center">
          <uv-button
            shape="circle"
            color="#4EA770"
            size="120rpx"
            icon="weixin-fill"
            icon-color="#fff"
            icon-size="60rpx"
            :throttle-time="1000"
            :custom-style="{
              width: '120rpx',
              height: '120rpx',
            }"
            @click="handleWxLogin"
          >
          </uv-button>
        </view>
        <view class="agreement">
          <uv-checkbox-group v-model="isPass" shape="circle">
            <uv-checkbox activeColor="#4EA770" :name="true">
              <view class="agree">
                我已阅读并同意
                <text @click.stop="handleAgreement('USER_POLICY')">《用户协议》</text>
                和
                <text @click.stop="handleAgreement('PRIVACY_POLICY')">《隐私协议》</text>
              </view>
            </uv-checkbox>
          </uv-checkbox-group>
        </view>
        <view
          class="app-icon"
          :style="{
            backgroundImage: `url(${appIcon})`,
          }"
        >
        </view>
      </template>
      <view v-else class="form-avatar">
        <uv-avatar :src="webSrc(forms.avatar)" size="216rpx" />
      </view>
    </view>
    <g-bind v-model:show="showBind" :code="wxcode" @success="getUserInfo" />
  </view>
</template>
<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { postLogin, getUser, winxinLogin } from "@/request/login.js";
import { webSrc } from "@/common/mothed.js";
import appIcon from "@/static/login/login.png"; // 图标

const formRef = ref(); // 表单ref
const forms = reactive({
  avatar: "", // 头像
  username: "", // 登录账号
  password: "", // 密码
});
const isPass = ref([]); // 是否同意协议
const rules = reactive({
  username: [
    {
      required: true,
      message: "请输入登录账号",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      min: 6,
      message: "密码长度不能小于6位",
      trigger: "blur",
    },
  ],
}); // 表单校验规则
const showPassword = ref(false); // 密码是否显示
const showBind = ref(false); // 显示绑定信息
const wxcode = ref(""); // 微信code

// 是否禁止登录
const disabled = computed(() => {
  let pass = false;
  if (isPass.value.length == 0) pass = false;
  if (isPass.value.find((i) => i)) pass = true;
  if (forms.avatar) pass = true;
  return !forms.username || !forms.password || !pass;
});

onMounted(() => {
  const form = uni.getStorageSync("userInfo");
  if (form && typeof form == "object") {
    forms.avatar = form.avatar;
    forms.username = form.userName;
    forms.password = "";
  }
});

// 登录
const handleLogin = () => {
  uni.$uv?.throttle(() => {
    formRef.value
      .validate()
      .then((valid) => {
        if (valid) {
          if (forms.avatar) {
            login();
          } else {
            if (isPass.value.length == 0) {
              uni.showModal({
                title: "协议",
                content: "是否已阅读并同意协议？",
                showCancel: true,
                success: ({ confirm }) => {
                  if (confirm) {
                    isPass.value = [true];
                    login();
                  }
                },
              });
            } else {
              login();
            }
          }
        }
      })
      .catch(() => {});
  }, 1000);
};

// 登录
const login = () => {
  postLogin(forms).then((res) => {
    if (res.code == 200) {
      uni.setStorageSync("TOKEN", res.token);
      getUserInfo();
    }
  });
};

// 微信登录
const handleWxLogin = () => {
  if (isPass.value.length == 0) {
    uni.showModal({
      title: "协议",
      content: "是否已阅读并同意协议？",
      showCancel: true,
      success: ({ confirm }) => {
        if (confirm) {
          isPass.value = [true];
          wxLogin();
        }
      },
    });
    return;
  }
  wxLogin();
};

// 微信登录
const wxLogin = () => {
  uni.login({
    provider: "weixin",
    onlyAuthorize: true,
    success: (e) => {
      winxinLogin({ code: e.code }).then((res) => {
        if (res.code == 200) {
          if (res.data.isBind) {
            uni.setStorageSync("TOKEN", res.data.token);
            getUserInfo();
          } else {
            wxcode.value = e.code;
            showBind.value = true;
            uni.showToast({
              title: "该微信未绑定账户，请先完成绑定",
              icon: "none",
            });
          }
        }
      });
    },
    fail: (err) => {
      console.log(err);
    },
  });
};

// 获取用户信息
const getUserInfo = () => {
  getUser().then((res) => {
    if (res.code == 200) {
      uni.setStorageSync("userInfo", res.user);
      uni.showToast({
        title: "登录成功",
        icon: "success",
        success: () => {
          setTimeout(() => {
            uni.reLaunch({
              url: "/pages/index/index",
            });
          }, 1500);
        },
      });
    }
  });
};

// 忘记密码
const handleForgot = () => {
  uni.navigateTo({
    url: "/pages/login/forgotPwd?type=forget",
  });
};

// 查看协议
const handleAgreement = (type) => {
  uni.navigateTo({
    url: "/pages/user/agreement?type=" + type,
  });
};

// 敏感信息处理
const sensitive = (str) => {
  let sensitiveStr = str.slice(0, 3) + "****" + str.slice(-4);
  return sensitiveStr;
};
</script>
<style lang="scss" scoped>
.login-page {
  width: 100%;
  height: 100vh;
  background: linear-gradient(180deg, #c4eee5 0%, #dbf9da 28%, #dcf8d9 100%);
  position: relative;

  &::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 1220rpx;
    background-image: url("@/static/login/bg1.png");
    background-size: 100% 100%;
    z-index: 1;
  }

  .login-title {
    position: absolute;
    bottom: 652px;
    left: 30rpx;
    color: #212121;
    font-size: 40rpx;
    line-height: 60rpx;
  }

  .login-body {
    width: 100%;
    height: 615px;
    background: linear-gradient(180deg, rgba(255, 255, 255, 0.57) 0%, #fff 100%);
    box-shadow: inset 0 2rpx 2rpx 2rpx #fff;
    border-radius: 20rpx 20rpx 0 0;
    position: absolute;
    bottom: 0;
    padding: 60rpx 40rpx;
    box-sizing: border-box;
    z-index: 2;

    .login-btn {
      font-size: 28rpx;
      color: #757575;
      margin-top: 44rpx;
    }

    .login-button {
      width: 100%;
      margin-top: 120rpx;
      box-shadow: 0 12rpx 30rpx 2rpx rgba(78, 167, 112, 0.5);
      height: 100rpx;
      border-radius: 100rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 32rpx;
      transition: all 0.3s;
      background: linear-gradient(90deg, #4ea770 0%, #5fc793 100%);
    }
    .disabled {
      background: linear-gradient(90deg, #b2d2bf 0%, #99dbb9 100%);
    }

    .app-icon {
      position: absolute;
      width: 348rpx;
      height: 348rpx;
      top: -270rpx;
      right: 40rpx;
      background-size: 100%;
      background-repeat: no-repeat;
      z-index: 2;
    }

    .login-username {
      height: 80rpx;
      line-height: 80rpx;
      color: #212121;
      font-size: 28rpx;
    }

    .form-avatar {
      position: absolute;
      top: -190rpx;
      left: 50%;
      padding: 10rpx;
      background-color: #fff;
      border-radius: 50%;
      transform: translateX(-50%);
    }
  }

  .agreement {
    position: absolute;
    bottom: 60rpx;
    left: 0;
    right: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .agree {
      color: #212121;
      font-size: 28rpx;

      text {
        color: #4ea770;
      }
    }
  }
}
</style>
